package com.kd.service.order;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kd.common.PageResult;
import com.kd.dao.CustomerMapper;
import com.kd.dao.ProductMapper;
import com.kd.entity.Customer;
import com.kd.entity.Order;
import com.kd.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;
import com.kd.dao.OrderMapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;


/**
 * 订单服务实现类，继承自 MyBatis-Plus 的 ServiceImpl
 * 1.通过oid找订单
 * 2.插入订单
 * 3.查看所有订单列表，with过滤条件   PageResult<Product> e0 e1 e2
 * 4.修改订单属性(仅老板e2可使用)
 * 5.更新订单状态 员工只能修改从1~2的修改,财务只能修改2~3，老板0~3都可以
 * 6.
 *
 */
@Service
@EnableScheduling // 启用定时任务
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private ProductMapper productMapper;
    private final Integer INSERT_SUCESS=1;


    // ===== 查询类方法 =====
    // 1. 基础CRUD操作
    @Override
    public Order getOrderById(Long oid) {
        return orderMapper.selectById(oid);
    }


@Override
@Transactional
public boolean insertOrder(Order order) {
    System.out.println("🔧 Service层 - 插入订单开始");

    try {
        // 生成订单ID
        if (order.getOid() == null) {
            Long orderId = generateOrderId();
            order.setOid(orderId);
        }

        // 计算总金额
        if (order.getPrice() != null && order.getQuantity() != null) {
            BigDecimal totalAmount = calculateTotalAmount(order.getPrice(), order.getQuantity());
            order.setTotalAmount(totalAmount);
        }

        // 设置默认值
        if (order.getStatus() == null) {
            order.setStatus(0);
        }
        if (order.getOrderDate() == null) {
            order.setOrderDate(new Date());
        }

        int result = orderMapper.insert(order);
        System.out.println("✅ 数据库插入结果，影响行数: " + result);

        if (result == 1) {
            System.out.println("🎉 订单插入成功！");
        } else {
            System.out.println("❌ 订单插入失败，影响行数: " + result);
        }

        return result == 1;

    } catch (Exception e) {
        System.out.println("❌ Service层异常: " + e.getMessage());
        e.printStackTrace();
        return false;
    }
}


//// 使用ThreadLocal解决SimpleDateFormat线程安全问题
//private static final ThreadLocal<SimpleDateFormat> dateFormatThreadLocal =
//        ThreadLocal.withInitial(()  -> new SimpleDateFormat("yyyyMMdd"));
//
//    private static final ThreadLocal<SimpleDateFormat> dateFormatDashThreadLocal =
//            ThreadLocal.withInitial(()  -> new SimpleDateFormat("yyyy-MM-dd"));
//    @Override
//    @Transactional
//    public boolean updateOrder(Order order) {
//        // 1. 查询现有订单（加锁）
//        Order existing = getOrderById(order.getOid());
//        if (existing == null) {
//            return false;
//        }
//        // 2. 更新订单
//        boolean updated = orderMapper.updateById(order)  > 0;
//        // 3. 状态变更处理
//        if (updated && existing.getStatus()  != order.getStatus())  {
//            try {
//                String dateStr = dateFormatThreadLocal.get().format(order.getOrderDate());
//                // 判断是激活还是取消激活
//                if (existing.getStatus()  == 0 && order.getStatus()  > 0) {
//                    // 激活：增加统计
//                    orderMapper.incrementDailyStats(
//                            dateStr,
//                            1, // 增加1个活跃订单
//                            order.getTotalAmount(),  // 增加金额
//                            order.getQuantity()
//                    );
//                } else if (existing.getStatus()  > 0 && order.getStatus()  == 0) {
//                    // 取消激活：减少统计
//                    orderMapper.decrementDailyStats(
//                            dateStr,
//                            -1, // 减少1个活跃订单
//                            order.getTotalAmount().negate(),  // 减少金额
//                            order.getQuantity()
//                    );
//                }
//            } finally {
//                dateFormatThreadLocal.remove();
//                dateFormatDashThreadLocal.remove();
//            }
//        }
//        return updated;
//    }
// 使用ThreadLocal解决SimpleDateFormat线程安全问题
private static final ThreadLocal<SimpleDateFormat> dateFormatThreadLocal =
        ThreadLocal.withInitial(()  -> new SimpleDateFormat("yyyyMMdd"));

    private static final ThreadLocal<SimpleDateFormat> dateFormatDashThreadLocal =
            ThreadLocal.withInitial(()  -> new SimpleDateFormat("yyyy-MM-dd"));
    @Override
    @Transactional
    public boolean updateOrder(Order order) {
        // 1. 查询现有订单（加锁）
        Order existing = getOrderById(order.getOid());
        if (existing == null) {
            return false;
        }
        // 2. 更新订单
        boolean updated = orderMapper.updateById(order)  > 0;
        // 3. 状态变更处理
        if (updated && existing.getStatus()  != order.getStatus())  {
            try {
                String date_str = dateFormatThreadLocal.get().format(order.getOrderDate());
                System.out.println(order);
                System.out.println(order.getCid());
                // 判断是激活还是取消激活
                if (existing.getStatus()  == 0 && order.getStatus()  > 0) {
                    // 激活：增加统计
                    orderMapper.updateDailyStats(
                            date_str,
                            1, // 增加1个活跃订单
                            order.getTotalAmount(),  // 增加金额
                            order.getQuantity()
                    );
                    // 2. 更新客户统计
                    customerMapper.updateCustomerStats(
                            order.getCid(),
                            1,
                            order.getTotalAmount(),
                            order.getQuantity()
                    );
                    // 3. 更新产品统计
                    productMapper.updateProductStats(
                            order.getPid(),
                            order.getQuantity()
                    );
                } else if (existing.getStatus()  > 0 && order.getStatus()  == 0) {
                    // 取消激活：减少统计
                    orderMapper.updateDailyStats(
                            date_str,
                            -1, // 减少1个活跃订单
                            order.getTotalAmount().negate(),  // 减少金额
                            -order.getQuantity()
                    );
                    customerMapper.updateCustomerStats(
                            order.getCid(),
                            -1,
                            order.getTotalAmount().negate(),
                            -order.getQuantity()
                    );
                    // 3. 更新产品统计
                    productMapper.updateProductStats(
                            order.getPid(),
                            -order.getQuantity()
                    );
                }
            } finally {
                dateFormatThreadLocal.remove();
                dateFormatDashThreadLocal.remove();
            }
        }
        return updated;
    }


    @Override
    @Transactional
    public boolean deleteOrder(Long oid) {
        return orderMapper.deleteById(oid)  > 0;
    }


    // 3. 订单查询
    @Override
    public PageResult<Order,Long> findOrdersWithFilters(
            Long cursor, Integer limit,
            Long oid, Integer cid, Integer pid,
            Date startOrderDate, Date endOrderDate,
            Date startEta, Date endEta,
            BigDecimal minPrice, BigDecimal maxPrice,
            Integer status) {
        if (limit == null || limit <= 0) limit = 10;

        QueryWrapper<Order> wrapper = new QueryWrapper<>();

        // 添加过滤条件
        if (oid != null) wrapper.like("oid",  oid);
        if (cid != null) wrapper.like("cid",  cid);
        if (pid != null) wrapper.like("pid",  pid);
        if (status != null) wrapper.eq("status",  status);
        if (startOrderDate != null) wrapper.ge("order_date",  startOrderDate);
        if (endOrderDate != null) wrapper.le("order_date",  endOrderDate);
        if (startEta != null) wrapper.ge("eta",  startEta);
        if (endEta != null) wrapper.le("eta",  endEta);
        if (minPrice != null) wrapper.ge("total_amount",  minPrice);
        if (maxPrice != null) wrapper.le("total_amount",  maxPrice);

        // 游标分页处理
        if (cursor != null && cursor > 0) {
            wrapper.lt("oid",  cursor);
        }
        wrapper.orderByDesc("oid");

        List<Order> orders = orderMapper.selectList(wrapper.last("LIMIT  " + (limit + 1)));

        boolean hasNext = orders.size()  > limit;
        List<Order> resultData = hasNext ? orders.subList(0,  limit) : orders;
        Long nextCursor = hasNext && !resultData.isEmpty()  ?
                resultData.get(resultData.size()  - 1).getOid() : null;

        return PageResult.of(resultData,  nextCursor, hasNext, limit);
    }


    // 3. 订单查询
    @Override
    public PageResult<Order,Long> findOrdersWitheFilters(
            Long cursor, Integer limit,
            Long oid, Integer cid, Integer pid,
            Integer status) {
        if (limit == null || limit <= 0) limit = 10;
        QueryWrapper<Order> wrapper = new QueryWrapper<>();

        // 添加过滤条件
        if (oid != null) wrapper.like("oid",  oid);
        if (cid != null) wrapper.like("cid",  cid);
        if (pid != null) wrapper.like("pid",  pid);
        if (status != null) wrapper.eq("status",  status);

        // 游标分页处理
        if (cursor != null && cursor > 0) {
            wrapper.lt("oid",  cursor);
        }
        wrapper.orderByDesc("oid");

        List<Order> orders = orderMapper.selectList(wrapper.last("LIMIT  " + (limit + 1)));

        boolean hasNext = orders.size()  > limit;
        List<Order> resultData = hasNext ? orders.subList(0,  limit) : orders;
        Long nextCursor = hasNext && !resultData.isEmpty()  ?
                resultData.get(resultData.size()  - 1).getOid() : null;

        return PageResult.of(resultData,  nextCursor, hasNext, limit);
    }

    // 3. 订单查询
    @Override
    public PageResult<Order,Long> findOrdersWithcFilters(
            Long cursor, Integer limit,
            Long oid, Integer cid, Integer pid,Integer status) {
        if (limit == null || limit <= 0) limit = 10;
        QueryWrapper<Order> wrapper = new QueryWrapper<>();

        // 添加过滤条件
        if (oid != null) wrapper.like("oid",  oid);
        if (cid != null) wrapper.like("cid",  cid);
        if (pid != null) wrapper.like("pid",  pid);
        if (status != null) wrapper.eq("status",  status);

        // 游标分页处理
        if (cursor != null && cursor > 0) {
            wrapper.lt("oid",  cursor);
        }
        wrapper.orderByDesc("oid");

        List<Order> orders = orderMapper.selectList(wrapper.last("LIMIT  " + (limit + 1)));

        boolean hasNext = orders.size()  > limit;
        List<Order> resultData = hasNext ? orders.subList(0,  limit) : orders;
        Long nextCursor = hasNext && !resultData.isEmpty()  ?
                resultData.get(resultData.size()  - 1).getOid() : null;

        return PageResult.of(resultData,  nextCursor, hasNext, limit);
    }



    // 4. 业务方法
    @Override
    public BigDecimal calculateTotalAmount(BigDecimal price, Integer quantity) {
        if (price == null || quantity == null) {
            return BigDecimal.ZERO;
        }
        return price.multiply(new  BigDecimal(quantity))
                .setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    // 5. OID生成方法
    @Override
    public Long generateOrderId() {
        System.out.println("🔢 开始生成订单ID - 当前方法返回类型: Long");
        System.out.println("🔢 方法签名: public Long generateOrderId()");

        try {
            // 1. 获取当前日期 yyyyMMdd
            String dateStr = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
            Long datePart = Long.parseLong(dateStr);
            // 2. 原子性获取序列号
            orderMapper.insertDailyOrder(dateStr);
            orderMapper.insertDailyStats(dateStr);
            int seq = orderMapper.getCurrentSeq(dateStr);

            // 3. 组合日期和序列号
            Long orderId = datePart * 1000 + 100 + seq;
            return orderId;

        } catch (Exception e) {
            System.out.println("❌ 生成订单ID失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("生成订单ID失败", e);
        }
    }














    // ============== 私有方法 ==============
    private boolean changeStatus(Long oid, Integer expectedStatus,
                                 Integer targetStatus, Integer operatorEid,
                                 Order additionalUpdates) {
        Order order = orderMapper.selectById(oid);
        if (order == null || !order.getStatus().equals(expectedStatus))  {
            return false;
        }

        Order update = additionalUpdates != null ? additionalUpdates : new Order();
        update.setOid(oid);
        update.setStatus(targetStatus);

        return orderMapper.updateById(update)  > 0;
    }

//


}
